/**
 * 产品详情页面交互逻辑
 */
import { fetchDataById, deleteDataItem } from '../../js/api.js';

/**
 * 从URL获取产品ID
 */
function getProductIdFromUrl() {
    const params = new URLSearchParams(window.location.search);
    const id = params.get('id');
    return id ? parseInt(id) : null;
}

/**
 * 渲染产品详情数据
 * @param {Object} data - 产品详情数据
 */
function renderProductDetail(data) {
    document.getElementById('productId').textContent = data.id;
    document.getElementById('productName').textContent = data.name;
    document.getElementById('categoryId').textContent = data.category_id;
    document.getElementById('productPrice').textContent = `￥${parseFloat(data.price).toFixed(2)}`;
    document.getElementById('productDescription').textContent = data.description || '-';
    document.getElementById('productImage').src = data.cover_image;
    document.getElementById('createdAt').textContent = new Date(data.created_at).toLocaleString();
    document.getElementById('updatedAt').textContent = new Date(data.updated_at).toLocaleString();

    // 设置上架状态
    const isOnSaleElement = document.getElementById('isOnSale');
    const statusClass = data.is_on_sale ? 'status-on' : 'status-off';
    const statusText = data.is_on_sale ? '已上架' : '未上架';
    isOnSaleElement.innerHTML = `<span class="status-badge ${statusClass}">${statusText}</span>`;
}

/**
 * 加载产品详情数据
 */
async function loadProductDetail() {
    const id = getProductIdFromUrl();
    if (!id) {
        alert('无效的产品ID');
        window.location.href = 'list.html';
        return;
    }

    try {
        const data = await fetchDataById(id);
        renderProductDetail(data);
    } catch (error) {
        console.error('加载产品详情失败:', error);
        alert('加载产品详情失败: ' + (error.message || '未知错误'));
    }
}

/**
 * 初始化删除按钮事件
 */
function initDeleteButton() {
    const deleteBtn = document.getElementById('deleteBtn');
    deleteBtn.addEventListener('click', async () => {
        const id = getProductIdFromUrl();
        if (!id) return;

        if (confirm('确定要删除此产品吗？此操作不可撤销！')) {
            try {
                const success = await deleteDataItem(id);
                if (success) {
                    alert('产品删除成功！');
                    window.location.href = 'list.html';
                }
            } catch (error) {
                console.error('删除产品失败:', error);
                alert('删除产品失败: ' + (error.message || '未知错误'));
            }
        }
    });
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', () => {
    loadProductDetail();
    initDeleteButton();
});